# -*- coding: utf-8 -*-

#===============================================================================
# GettingTasksDone.com project Views file
# 2007-10-26: Sergeyev V.V.
#===============================================================================

from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect, HttpResponse, Http404
from django import newforms as forms
from django.newforms import form_for_instance, form_for_model, save_instance, form_for_fields
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.template import RequestContext
from django.conf import settings
from django.core.mail import send_mail
from poplib import POP3
from django.views.decorators.cache import cache_page, cache_control
#from django.core.cache import cache

import datetime
import time
import math
import csv

from urlparse import urlparse

from pds.models import *
from pds.routines import *

#------------------------------------------------------------------------------ 
def iphone_prefix(iphone):
    prefix = ""
    if iphone:
        prefix = "iphone/"
    return prefix

#------------------------------------------------------------------------------ 
# Авторизация
#------------------------------------------------------------------------------ 
def login_user(request, iphone=False):
    "Implements login action"

    if request.method == "POST":
        username = request.POST["username"]
        password = request.POST["password"]
        
        try:
            user = authenticate(username=username, password=password)
            if user is None:
                raise Exception
            
            login(request, user)
            
            return HttpResponseRedirect("/%s" % iphone_prefix(iphone))
        except:
            error_message = "Uncorrect account, user name or password! Please try again."
            return render_to_response("%slogin.html" % iphone_prefix(iphone), {"error_message" : error_message})
    else:
        return render_to_response("login.html")

#------------------------------------------------------------------------------
def logout_user(request, iphone=False):
    "Implements logout action"
    
    if request.session.get('deleted_name'):
        del request.session['deleted_name']
    
    if request.session.get('deleted_id'):
        del request.session['deleted_id']
    
    if request.session.get('deleted_model'):
        del request.session['deleted_model']
    
    request.session['openids'] = []
    
    logout(request)
    
    return HttpResponseRedirect("/%s" % iphone_prefix(iphone))

#------------------------------------------------------------------------------
@cache_page
def registration(request, iphone=False):
    "Registration"
    
    error_message = ""
    
    if request.method == "POST":
        reg_form = RegistrationForm(request.POST)
        if reg_form.is_valid():
            try:
                username = request.POST["username"]
                password = request.POST["password"]
                user = User.objects.create_user(username, "", password)
                user = authenticate(username=username, password=password)
                if user is None:
                    raise Exception
            
                login(request, user)
                
                welcome_new_user(user)
                
                return HttpResponseRedirect("/%s" % iphone_prefix(iphone))
            except:
                error_message = "Can't create user with given name. Try another username please."
    else:
        reg_form = RegistrationForm()
    
    content = {
               "reg_form": reg_form,
               "error_message": error_message,
               "motivation": get_motivation(),
               }
    
    return render_to_response("%sregistration.html" % iphone_prefix(iphone), content, context_instance=RequestContext(request))

#------------------------------------------------------------------------------ 
@login_required
def profile(request):
    "Settings/User's profile page"
    
    user_profile = request.user.profile
    UserForm = form_for_instance(user_profile, formfield_callback=item_field_callback)
    
    error_message = ""
    
    if request.method == "POST":
        user_form = UserForm(request.POST)
        if user_form.is_valid():
            user_form.save()
            return HttpResponseRedirect('/')
    else:
        user_form = UserForm()
        
    content = {
               "user_form": user_form,
               "error_message": error_message,
               }
    
    return render_to_response("profile.html", content, context_instance=RequestContext(request))

#------------------------------------------------------------------------------
def index(request, template='index', iphone=False):
    "Main page"
    
    if not request.user.is_authenticated():
        if request.openid:
            openid = request.openid.openid
            user_profiles = Profile.objects.filter(openid__iexact=openid)
            if user_profiles:
                for user_profile in user_profiles:
                    username = user_profile.user.username
                user = User.objects.get(username=username)
                user.backend = "django.contrib.auth.backends.ModelBackend"
                #user = authenticate(username=username, password=password)
                
                login(request, user)
                
                return HttpResponseRedirect("/%s" % iphone_prefix(iphone))
            else:
                params = urlparse(openid)
                username = params[1][:30]
                password = User.objects.make_random_password()
                user = User.objects.create_user(username, "", password)
                user = authenticate(username=username, password=password)
                if user is None:
                    raise Exception
            
                login(request, user)
                
                user_profile = user.profile
                user_profile.openid = openid
                user_profile.save()
                
                welcome_new_user(user)
                
                return HttpResponseRedirect("/%s" % iphone_prefix(iphone))
        else:
            return render_to_response("%slogin.html" % iphone_prefix(iphone))
    
    tasks, projects, customers = None, None, None
    
    if template == 'index':
        tasks = Task.objects.filter(user__exact=request.user).filter(deleted__exact=False).order_by('-task_date', 'name')
    elif template == 'projects':
        projects = Project.objects.filter(user__exact=request.user).filter(deleted__exact=False).order_by('name')
    elif template == 'customers':
        customers = Customer.objects.filter(user__exact=request.user).filter(deleted__exact=False).order_by('name')
    
    deleted_name = request.session.get('deleted_name')
    
    content = {
               "customers": customers,
               "projects": projects,
               "tasks": tasks,
               "motivation": get_motivation(),
               }
    
    return render_to_response("%s%s.html" % (iphone_prefix(iphone), template), content, context_instance=RequestContext(request, {'deleted_name': deleted_name}))

#------------------------------------------------------------------------------
#@login_required
def tasks(request, iphone=False):
    return HttpResponseRedirect('/%s' % iphone_prefix(iphone))

#------------------------------------------------------------------------------
@login_required
def new_item(request, model_name, iphone=False):
    "New item: task, project or customer"
    
    user = request.user
    ItemForm = form_for_model(eval(model_name), formfield_callback=item_field_callback)
    new_item = None
    
    if request.method == "POST":
        item_form = ItemForm(request.POST)
    
        if item_form.is_valid():
            new_item = item_form.save(False)
            new_item.user = request.user
            new_item.deleted = False
            new_item.save()
            return HttpResponseRedirect('/%s%ss/' % (iphone_prefix(iphone), model_name.lower()))
    else:
        item_form = ItemForm()
    
    item_form.fields["project"] = forms.ModelChoiceField(Project.objects.filter(user__exact=user), initial=None)
    
    content = {
               "item": new_item,
               "model_name": model_name,
               "form": item_form,
               }
    
    return render_to_response("%sitem.html" % iphone_prefix(iphone), content, context_instance=RequestContext(request))

#------------------------------------------------------------------------------ 
@login_required
def edit_item(request, item_id, model_name, iphone=False):
    'Universal function for editing Tasks, Customers, Projects'
    
    user = request.user
    
    try:
        item = eval(model_name).objects.get(pk=item_id)
    except:
        return HttpResponseRedirect('/%s%ss/' % (iphone_prefix(iphone), model_name.lower()))
    
    # check - if this item owned by current user?
    if request.user != item.user:
        return HttpResponseRedirect('/%s' % iphone_prefix(iphone))
    
    # if we have POST data, we save item
    if request.method == "POST":
        ItemForm = form_for_model(eval(model_name), formfield_callback=item_field_callback)
        item_form = ItemForm(request.POST)
    
        if item_form.is_valid():
            save_instance(item_form, item, True)
           
        if request.POST['save_and_stay'] == 'yes':
            return "ok"
        else:
            return HttpResponseRedirect('/%s%ss/' % (iphone_prefix(iphone), model_name.lower()))
    
    ItemForm = form_for_instance(item, formfield_callback=item_field_callback)
    
    # for Task's form we adding "Project" field 
    if model_name == 'Task':
        project_id = None
        if item.project:
            project_id = item.project.id
        ItemForm.base_fields["project"] = forms.ModelChoiceField(Project.objects.filter(user__exact=user), initial=project_id)
    
    # for both Task's and Project's form we adding "Customer" field    
    if (model_name =='Project'): # or (model_name == 'Task'):
        customer_id = None
        if item.customer:
            customer_id = item.customer.id
        ItemForm.base_fields["customer"] = forms.ModelChoiceField(Customer.objects.filter(user__exact=user), initial=customer_id)
    
    item_form = ItemForm()
    content = {
               "item": item,
               "model_name": model_name,
               "form": item_form,
               }
    
    return render_to_response("%sitem.html" % iphone_prefix(iphone), content, context_instance=RequestContext(request))

#------------------------------------------------------------------------------ 
@login_required
def edit_inline(request, model_name):
    user = request.user
    
    if request.method == "GET":
        item_id = request.GET['item_id']
        item = eval(model_name).objects.get(pk=item_id)
        
        ItemForm = form_for_instance(item, formfield_callback=item_field_callback)
        project_id = None
        if item.project:
            project_id = item.project.id
        ItemForm.base_fields["project"] = forms.ModelChoiceField(Project.objects.filter(user__exact=user), initial=project_id)
        
        item_form = ItemForm()
        content = {
               "form": item_form,
               "item": item,
               }
        return render_to_response("item_form.html", content, context_instance=RequestContext(request))
    elif request.method == "POST":
        item_id = request.POST['item_id']
        item = eval(model_name).objects.get(pk=item_id)
        ItemForm = form_for_model(eval(model_name), formfield_callback=item_field_callback)
        item_form = ItemForm(request.POST)
    
        if item_form.is_valid():
            save_instance(item_form, item, True)
        #return "ok"
        content = {
               "task": item,
               }
        return render_to_response("item_inline.html", content, context_instance=RequestContext(request))

#------------------------------------------------------------------------------ 
@login_required
def get_inline(request, model_name):
    if request.method == "GET":
        #time.sleep(2)
        item_id = request.GET['item_id']
        item = eval(model_name).objects.get(pk=item_id)
        
        content = {
               "task": item,
               }
        return render_to_response("item_inline.html", content, context_instance=RequestContext(request))

#------------------------------------------------------------------------------ 
@login_required
def archive_item(request, item_id, model_name):
    
    item = eval(model_name).objects.get(pk=item_id)
    item.deleted = True
    item.save()
    
    request.session['deleted_name'] = model_name #item.name
    request.session['deleted_id'] = item_id
    request.session['deleted_model'] = model_name
    
    return HttpResponseRedirect('/%ss/' % model_name.lower())

#------------------------------------------------------------------------------ 
@login_required
def delete_item(request, item_id, model_name):
    
    item = eval(model_name).objects.get(pk=item_id)
    item.delete()
    
    return HttpResponseRedirect('/%ss/' % model_name.lower())

#------------------------------------------------------------------------------ 
@login_required
def unarchive_item(request, item_id, model_name):
    
    item = eval(model_name).objects.get(pk=item_id)
    item.deleted = False
    item.save()
    
    return HttpResponseRedirect('/%ss/' % model_name.lower())

#------------------------------------------------------------------------------ 
@login_required
def undo(request, iphone=False):
    deleted_id = request.session['deleted_id']
    deleted_model = request.session['deleted_model']
    
    if deleted_id and deleted_model:
        if isinstance(deleted_id, list):
            for item_id in deleted_id:
                item = eval(deleted_model).objects.get(pk=item_id)
                item.deleted = False
                item.save()
        else:
            item = eval(deleted_model).objects.get(pk=deleted_id)
            item.deleted = False
            item.save()
    
    request.session['deleted_name'] = None
    request.session['deleted_id'] = None
    request.session['deleted_model'] = None
        
    return HttpResponseRedirect('/%s%ss/' % (iphone_prefix(iphone), deleted_model.lower()))

#------------------------------------------------------------------------------
@login_required 
def task_is_done(request):
    if request.method == "POST":
        task_id = request.POST['id']
        task = Task.objects.get(pk=task_id)
        if task.done:
            task.done = False
        else:
            task.done = True
        task.save()

#------------------------------------------------------------------------------ 
@login_required
def archive_all_done_tasks(request, iphone=False):
     
    items_id = []
    tasks = Task.objects.filter(user__exact=request.user).filter(deleted__exact=False)
    
    for item in tasks:
         if item.done:
             item.deleted = True
             item.save()
             items_id.append(item.id)
    
    if items_id:
        request.session['deleted_name'] = "%i done tasks" % len(items_id)
        request.session['deleted_id'] = items_id
        request.session['deleted_model'] = 'Task'

    return HttpResponseRedirect('/%s' % iphone_prefix(iphone))

#------------------------------------------------------------------------------ 
@login_required
def view_archived_tasks(request):
    tasks = Task.objects.filter(user__exact=request.user).filter(deleted__exact=True)

    content = {
               "tasks": tasks,
               }
    
    return render_to_response("archived_tasks.html", content, context_instance=RequestContext(request))

#------------------------------------------------------------------------------
@login_required 
def project_detail(request):
    project_id = request.POST['project_id']
    
    if project_id == 'None':
        tasks = Task.objects.filter(user__exact=request.user, project__isnull=True, done=True).order_by('-task_date')
    else:
        tasks = Task.objects.filter(project__exact=project_id, done=True).order_by('-task_date')
    
    content = {
              "tasks": tasks,
              }
    
    return render_to_response("achievements_detail.html", content, context_instance=RequestContext(request))

#------------------------------------------------------------------------------
@cache_page 
def static_pages(request, page_name, iphone=False):
    "Static pages"
    
    return render_to_response("%s%s.html" % (iphone_prefix(iphone), page_name), {}, context_instance=RequestContext(request))

#------------------------------------------------------------------------------ 
def about_image(request, image_name):
    "About service page, image viewing"
    
    return render_to_response("about_image.html", {'image': image_name}, context_instance=RequestContext(request))

#------------------------------------------------------------------------------ 
def terms_of_service(request, iphone=False):
    return render_to_response("%sterms.html" % iphone_prefix(iphone), {}, context_instance=RequestContext(request))

#------------------------------------------------------------------------------ 
def get_ticket_form(request):
    "Return ticket form via AJAX"
    
    ticket_form = TicketForm()
    
    content = {
               "ticket_form": ticket_form,
               }
    
    return render_to_response("ticket_form.html", content, context_instance=RequestContext(request))

#------------------------------------------------------------------------------ 
def post_ticket(request):
    "Post ticket to us"
    
    if request.method == "POST":
        ticket_form = TicketForm(request.POST)
        if ticket_form.is_valid():
            params = {
                      'username': ticket_form.clean_data['username'],
                      'comment':  ticket_form.clean_data['comment'],
                      }
            ticket = Ticket(**params)
            ticket.save()
            
            return render_to_response("post_ticket.html", {}, context_instance=RequestContext(request))
            
    content = {
               "ticket_form": ticket_form,
               }
    
    return render_to_response("post_ticket.html", content, context_instance=RequestContext(request))

#------------------------------------------------------------------------------
@login_required 
def print_tasks(request):
    tasks = Task.objects.filter(user__exact=request.user).filter(deleted__exact=False).order_by('-task_date')
    
    content = {
               "tasks": tasks,
               }
    
    return render_to_response("print_tasks.html", content, context_instance=RequestContext(request))

#------------------------------------------------------------------------------
@login_required 
def export_tasks(request):
    "Export tasks into CSV"
    tasks = Task.objects.filter(user__exact=request.user).filter(deleted__exact=False).order_by('-task_date')
    
    response = HttpResponse(mimetype='text/csv')
    response['Content-Disposition'] = 'attachment; filename=Active_tasks.csv'
    #вывод заголовочной строки
    writer = csv.writer(response)
    writer.writerow(["Done", "Summary", "Project", "Description", "Date", "Time spent"])
    #вывод строк событий
    for task in tasks:
        writer.writerow([str(task.done), task.name, task.project, task.text, task.task_date, task.time_spent])
    
    return response

#------------------------------------------------------------------------------
@login_required 
def export_projects(request):
    "Export projects into CSV"
    projects = Project.objects.filter(user__exact=request.user).filter(deleted__exact=False).order_by('name')
    
    response = HttpResponse(mimetype='text/csv')
    response['Content-Disposition'] = 'attachment; filename=Active_projects.csv'
    #вывод заголовочной строки
    writer = csv.writer(response)
    writer.writerow(["Project name", "Customer", "Hour rate", "Description"])
    #вывод строк событий
    for project in projects:
        writer.writerow([project.name, str(project.customer), project.hour_rate, project.text])
    
    return response

#------------------------------------------------------------------------------
@login_required 
def export_customers(request):
    "Export customers into CSV"
    customers = Customer.objects.filter(user__exact=request.user).filter(deleted__exact=False).order_by('name')
    
    response = HttpResponse(mimetype='text/csv')
    response['Content-Disposition'] = 'attachment; filename=Customers.csv'
    #вывод заголовочной строки
    writer = csv.writer(response)
    writer.writerow(["Name", "e-Mail", "Description"])
    #вывод строк событий
    for customer in customers:
        writer.writerow([customer.name, customer.email, customer.text])
    
    return response

#------------------------------------------------------------------------------
@login_required 
def my_achievements(request):
    'Achivments is a report, showing time you have spent on different projects.'
    content = None

    projects = Project.objects.filter(user__exact=request.user)
    
    content = {
                "projects": projects,
               }
    
    return render_to_response("achievements.html", content, context_instance=RequestContext(request))

#------------------------------------------------------------------------------ 
@login_required
def achievements_ajax(request):
    content = None
    filter_by_project = request.POST["filter"]
    time_filter = request.POST["time"]
    
    if filter_by_project == "any":
        tasks = Task.objects.filter(user__exact=request.user, done=True)
    elif filter_by_project == "":
        tasks = Task.objects.filter(user__exact=request.user, done=True).filter(project__isnull=True)
    else:
        tasks = Task.objects.filter(user__exact=request.user, done=True).filter(project__exact=filter_by_project)
    
    if tasks:
        achivements = {}
        total_time = 0.0
        
        for task in tasks:
            total_time += float(task.time_spent)
            
            if task.project:
                project_name = task.project.name
                project_id = task.project.id
                hour_rate = task.project.hour_rate
            else:
                project_name = "Simple tasks"
                project_id = None
                hour_rate = 0.0
            achivement = Achivement(project_name, project_id, float(hour_rate), float(task.time_spent), task.task_date, task.task_date)
            
            if  project_name in achivements:
                achivements[project_name].time_spent += float(task.time_spent)
                if not achivements[project_name].first_task:
                    achivements[project_name].first_task = task.task_date
                achivements[project_name].last_task = task.task_date
            else:
                achivements[project_name] = achivement
        
        if total_time > 0:
            for key in achivements.keys():
                achivements[key].percent = int(achivements[key].time_spent / total_time * 100) * 4
                achivements[key].money_cost = achivements[key].time_spent * achivements[key].hour_rate
                if achivements[key].money_cost == 0.0:
                    achivements[key].money_cost = None

        values = achivements.values()
        #values.sort(key=values.project)
        
        content = {
                   "achivements": values,
                   }
    
    return render_to_response("achievements_ajax.html", content, context_instance=RequestContext(request))

#------------------------------------------------------------------------------
@login_required 
def share_tasks(request, iphone=False):
    """Page where user may shoose - share tasks or not. And specify people, who able to view shared tasks."""
    
    if request.method == "POST":
        if "share_tasks" in request.POST:
            share_tasks = True
            share_users = request.POST["share_users"]
            share_link = "http://gettingtasksdone.com/user/%s/" % request.user
            message = "Your tasks now accessible at:"
            share_link = "http://gettingtasksdone.com/user/%s/" % request.user
            share_link2 = "http://gettingtasksdone.com/iphone/user/%s/" % request.user
        else:
            share_tasks = False
            share_users = ""
            message = "Your tasks now private"
            share_link = ""
            share_link2 = ""
        
        user_profile = request.user.profile
        user_profile.tasks_shared = share_tasks
        user_profile.share_users = share_users
        user_profile.save()
        
        
        
        content = {
                "message": message,
                "share_link": share_link,
                "share_link2": share_link2,
                }
        return render_to_response("%sop_done.html" % iphone_prefix(iphone), content, context_instance=RequestContext(request))
    else:
        message = ""
        
        projects = Project.objects.filter(user__exact=request.user)
    
        form = None #SendmailForm()
    
        share_link = "http://gettingtasksdone.com/user/%s/" % request.user
        share_link2 = "http://gettingtasksdone.com/iphone/user/%s/" % request.user
    
        tasks_shared = request.user.profile.tasks_shared
        share_users = request.user.profile.share_users
    
        content = {
                "message": message,
                "form": form,
                "projects": projects,
                "share_link": share_link,
                "share_link2": share_link2,
                "share_users": share_users,
                "tasks_shared": tasks_shared,
                }
    
        return render_to_response("%ssharetasks.html" % iphone_prefix(iphone), content, context_instance=RequestContext(request))    

#------------------------------------------------------------------------------ 
def user_page(request, user_name, iphone=False):
    """Public page with shared tasks"""
    
    visitor = ""
    if request.user.is_authenticated():
        visitor = request.user.username

    user = User.objects.get(username=user_name)
    if not user:
        return HttpResponseRedirect("/%s" % iphone_prefix(iphone))
    
    tasks = None
    
    if user.profile.tasks_shared:
        
        if user.profile.share_users == "":
            tasks = Task.objects.filter(user__exact=user).filter(deleted__exact=False).order_by('-task_date', 'name')
        else:
            share_users = user.profile.share_users.splitlines() #.split(',')
        
            if visitor in share_users:
                tasks = Task.objects.filter(user__exact=user).filter(deleted__exact=False).order_by('-task_date', 'name')
            else:
                tasks = None
    
    content = {
               "tasks": tasks,
               "user_name": user,
               }
    
    return render_to_response("%suserpage.html" % iphone_prefix(iphone), content, context_instance=RequestContext(request))    

#------------------------------------------------------------------------------ 
def hottasks(request, iphone=False):
    ""
    HotForm = form_for_model(HotTask)
    message = ""
    hot_tasks = HotTask.objects.filter(deleted__exact=False).order_by('-saved_count')
    
    if request.method == "POST":
        hot_form = HotForm(request.POST)
        if hot_form.is_valid():
            new_item = hot_form.save(False)
            new_item.user = request.user
            new_item.saved_count = 0;
            new_item.deleted = False
            new_item.save()
            message = "Thank you!"
    else:
        hot_form = HotForm()

    content = {
            "tasks": hot_tasks,
            "form": hot_form,
            "message": message,
            #"adds": get_adds(),
            }
    
    return render_to_response("%shottasks.html" % iphone_prefix(iphone), content, context_instance=RequestContext(request))

#------------------------------------------------------------------------------
@login_required 
def add_from_hottask(request, task_id, iphone=False):
    "Creates a new task from hot task"
    
    user = request.user
    
    hot_task = HotTask.objects.get(pk=task_id)
    hot_task.saved_count += 1;
    hot_task.save()
    
    new_task = Task(user=user, name=hot_task.name, time_spent=0.0, text="", done=False, deleted=False)
    new_task.save()
    
    return HttpResponseRedirect("/%s" % iphone_prefix(iphone))

#------------------------------------------------------------------------------
@login_required 
def statistics(request):
    user = request.user
    
    HttpResponseRedirect('/')
    
    #tasks = task_is_done.objects.all()
    users = User.objects.all()
    
    have_1task = 0
    have_2task = 0
    have_3task = 0
    have_4task = 0
    
    for g_user in users:
        count = Task.objects.filter(user__exact=g_user).count()
        if count == 1:
            have_1task += 1
        if count == 2:
            have_2task += 1
        if count == 3:
            have_3task += 1
        if count > 3:
            have_4task += 1
    
    content = {
               "have_1task": have_1task,
               "have_2task": have_2task,
               "have_3task": have_3task,
               "have_4task": have_4task,
               }
    
    return render_to_response("stat.html", content, context_instance=RequestContext(request))

#------------------------------------------------------------------------------ 
def sitemap(request):
    return render_to_response("sitemap.html", {}, context_instance=RequestContext(request))

#------------------------------------------------------------------------------ 
def check_login(request):
    "Check login's availability"
    
    login = request.POST["login"]
    try:
        page_user = User.objects.get(username=login)
        return HttpResponse("<b style='color:red'>This user name is already taken!</b>")
    except:
        return HttpResponse("<b style='color:green'>This user name is available!</b>")

#------------------------------------------------------------------------------
#@login_required 
def go_offline(request, iphone=False):
    "Offline mode"
    tasks = None
    user = request.user
    if user.is_authenticated():
        tasks = Task.objects.filter(user=request.user).filter(deleted=False).order_by('-task_date', 'name')
    deleted_name = request.session.get('deleted_name')
    
    content = {
               "tasks": tasks,
               "motivation": "OFFLINE",
               }
    
    return render_to_response("%soffline.html" % iphone_prefix(iphone), content, context_instance=RequestContext(request, {'deleted_name': deleted_name}))

#------------------------------------------------------------------------------ 
@login_required 
def sync_data(request, iphone=False):
    "Sync data"
    user = request.user
    count = int(request.POST['count'])
    deleted_ids = request.POST['deleted_ids']
    if deleted_ids != "":
        deleted_ids = deleted_ids.split(",")
        for id in deleted_ids:
            if id != "0":
                item = Task.objects.get(pk=id)
                if item.user == user:
                    item.deleted = True
                    item.save()
    
    for i in range(0, count):
        id = int(request.POST['id%i' % i])
        name = request.POST['name%i' % i]
        done = (request.POST['done%i' % i] == "done")
        if id == 0:
            Task(user=user, name=name, time_spent=0.0, done=done, deleted=False).save()
        else:
            item = Task.objects.get(pk=id)
            if item.user == user:
                item.name = name
                item.done = done
                item.save()
    
    return HttpResponse("ok")

#------------------------------------------------------------------------------
